package com.yanghongyue.reggie.controller;

import com.yanghongyue.reggie.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * @author HongyueYang
 */
@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${reggie.path}")
    private String basePath;
    //文件上传
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
        //获取原始文件名
        String originalFilename = file.getOriginalFilename();
        //截取文件后缀名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //使用UUID重新生成文件名，防止文件名称重复
        String fileName = UUID.randomUUID().toString() + suffix;
        //创建一个file对象 代表文件存放目录
        File f = new File(basePath);
        //判断目录是否存在
        if (!f.exists()) {
            //不存在则创建
            f.mkdir();
        }
        //将临时文件转存到指定位置
        file.transferTo(new File(basePath + fileName));
        //返回文件名
        return R.sucess(fileName);
    }
    //文件加载
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {
        //创建文件输入流
        FileInputStream fis = new FileInputStream(new File(basePath + name));
        //通过响应对象获取一个能给客户端响应内容的输出流
        ServletOutputStream os = response.getOutputStream();
        //设置响应的内容类型
        response.setContentType("image/jpeg");
        //循环读取指定文件
        int len = 0;
        byte[] bytes = new byte[1024];
        while ((len = fis.read(bytes))!=-1){
            //将读取到的内容写入到输出流中
            os.write(bytes,0,len);
            //刷新
            os.flush();
        }
        //关闭资源
        fis.close();
        os.close();
    }
}
